package controller;

import common.AjaxResult;
import common.BaseEntity;
import dto.AuthorizeDTO;
import entity.Role;
import entity.User;
import entity.UserRole;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import service.impl.RoleServiceImpl;
import service.impl.UserServiceImpl;

import java.util.*;

/**
 * Created by asus on 2017/6/18.
 */
@RequestMapping("/authorize")
@Controller
public class UserAuthorizeController {
    @Autowired
    private UserServiceImpl userService;

    @Autowired private RoleServiceImpl roleService;

    @RequestMapping("/index")
    @ResponseBody
    public void index(){
        //return "/security/authorize/zuthorize_list";
    }

    @RequestMapping("/getAuthorizes")
    public List<AuthorizeDTO> getAuthorizes(Integer page, Integer rows){
        List<UserRole> userRoles = userService.getUserRoles(page, rows);
        Collection<Long> userIds = new HashSet<Long>();
        Collection<Long> roleIds = new HashSet<Long>();
        for(UserRole ur : userRoles){
            userIds.add(ur.getUserId());
            roleIds.add(ur.getRoleId());
        }

        Collection<User> users =  userService.getUsers(userIds);
        List<Role> roles = roleService.getRoles(roleIds);

        Map<Long,User> userMap = BaseEntity.idEntityMap(users);
        Map<Long,Role> roleMap = BaseEntity.idEntityMap(roles);

        List<AuthorizeDTO> authorizeDTOS = new LinkedList<AuthorizeDTO>();
        for(UserRole ur : userRoles){
            AuthorizeDTO authorizeDTO = new AuthorizeDTO();
            authorizeDTO.setRoleId(ur.getRoleId());
            authorizeDTO.setUserId(ur.getUserId());
            authorizeDTO.setUserName(userMap.get(ur.getUserId()).getName());
            authorizeDTO.setUserRoleId(ur.getId());
            authorizeDTO.setRoleName(roleMap.get(ur.getRoleId()).getName());
            authorizeDTOS.add(authorizeDTO);
        }

        return authorizeDTOS;
    }

    /**
     * 根据用户id查询用户和角色的 对应关系
     * @param userId
     * @return
     */
    public List<UserRole> getUserRoleBuUserId(Long userId){
        return userService.getUserRolesByUserId(userId);
    }

    /**
     * 设置权限
     * @param user
     * @param roleIds
     * @return
     */
    public AjaxResult setAuthorize(User user, String roleIds)
    {
        String[] temp = roleIds.split(",");
        Long[] roleIdArray  = new Long[temp.length];
        for(int i=0;i<roleIdArray.length;i++){
            roleIdArray[i] = Long.valueOf(temp[i]);
        }
        userService.addUserRole(user.getId(), roleIdArray);
        return AjaxResult.success();
    }
}
